package com.ctw.tinyservices.id.server.handler;

import com.ctw.tinyservices.id.common.utils.LogUtils;
import com.ctw.tinyservices.id.core.IdGenerator;
import com.ctw.tinyservices.id.server.lifecycle.AbstractIdServerLifecycle;

import java.util.LinkedList;
import java.util.List;

/**
 * @author TongWei.Chen 2022/3/17 19:29
 *
 * id处理器，抽象类
 **/
public abstract class AbstractIdHandler extends AbstractIdServerLifecycle {

    protected IdGenerator idGenerator;

    public Long getId(String bizType) {
        return idGenerator.getId(bizType);
    }

    public List<Long> listId(String bizType, int num) {
        LinkedList<Long> ids = new LinkedList<>();
        for (int i = 0; i < num; i ++) {
            try {
                Long id = getId(bizType);
                if (null == id) {
                    LogUtils.warn(AbstractIdHandler.class, "Failed to get id, If it is number segment mode, it may be no bizType record exists or double buffer is full");
                    continue;
                }
                ids.offer(id);
            } catch (Exception e) {
                // ignore
                LogUtils.warn(AbstractIdHandler.class, "Failed to get id, {}", e.getMessage());
                continue;
            }
        }
        return ids;
    }
}
